<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listPositions, addPosition, updatePosition, deletePosition, getAllTeachers } from '@/api/position'
import { Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue'

const filters = ref({
  name: '',
  location: '',
  status: null,
  page: 1,
  size: 8
})

const tableData = ref({
  records: [],
  total: 0
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const form = reactive({
  id: null,
  name: '',
  description: '',
  location: '',
  salary: '',
  time: '',
  status: 0,
  teacherId: null
})

const teachers = ref([])

const loading = ref(false)

const rules = {
  name: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入工作内容', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入工作地点', trigger: 'blur' }
  ],
  salary: [
    { required: true, message: '请输入薪资', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的薪资金额', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请输入工作时间', trigger: 'blur' }
  ],
  teacherId: [
    { required: true, message: '请选择发布教师', trigger: 'change' }
  ]
}

const searchTimeout = ref(null)

const handleSearch = () => {
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value)
  }
  searchTimeout.value = setTimeout(() => {
    filters.value.page = 1
    fetchData()
  }, 300)
}

const fetchTeachers = async () => {
  try {
    const res = await getAllTeachers()
    if (res.code === 0) {
      teachers.value = res.data
    }
  } catch (e) {
    ElMessage.error('获取教师列表失败')
  }
}

onMounted(() => {
  fetchTeachers()
})
const formRef = ref()


const fetchData = async () => {
  loading.value = true
  try {
    const res = await listPositions(filters.value)
    if (res.code === 0) {
      tableData.value = {
        records: res.data.records,
        total: res.data.total
      }
      filters.value.page = res.data.current
      filters.value.size = res.data.size
    }
  } catch (e) {
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (val) => {
  filters.value.page = val
  fetchData()
}

const resetFilters = () => {
  ElMessageBox.confirm('确定要重置所有筛选条件吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    filters.value = { 
      name: '', 
      location: '', 
      status: null, 
      page: 1, 
      size: 8 
    }
    fetchData()
  }).catch(() => {})
}



const handleAdd = () => {
  dialogTitle.value = '新增岗位'
  isEdit.value = false
  Object.assign(form, { 
    id: null, 
    name: '', 
    description: '', 
    location: '', 
    salary: '', 
    time: '', 
    status: 0,
    teacherId: null
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑岗位'
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该岗位吗？', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await deletePosition(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const submitData = {
      ...form,
      teacherId: Number(form.teacherId)
    }
    if (isEdit.value) {
      await updatePosition(submitData)
      ElMessage.success('修改成功')
    } else {
      await addPosition(submitData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (e) {
    if (e instanceof Error) {
      ElMessage.error(isEdit.value ? '修改失败' : '新增失败')
    }
  }
}

fetchData()
</script>

<template>
  <div class="jobs-page">
    <el-form :inline="true" :model="filters" class="filter-form" @submit.prevent>
      <el-form-item label="岗位名称">
        <el-input 
          v-model="filters.name" 
          placeholder="输入岗位名称" 
          clearable 
          @input="handleSearch"
          @clear="handleSearch"
        />
      </el-form-item>
      <el-form-item label="工作地点">
        <el-input 
          v-model="filters.location" 
          placeholder="输入工作地点" 
          clearable 
          @input="handleSearch"
          @clear="handleSearch"
        />
      </el-form-item>
      <el-form-item label="状态" style="min-width: 180px;">
        <el-select 
          v-model="filters.status" 
          placeholder="全部" 
          clearable 
          style="width: 140px;"
          @change="handleSearch"
        >
          <el-option label="可申请" :value="0" />
          <el-option label="不可申请" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData" :icon="Search">查询</el-button>
        <el-button @click="resetFilters" :icon="Refresh">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right;margin-left:auto;">
        <el-button type="success" @click="handleAdd" :icon="Plus" circle></el-button>
      </el-form-item>
    </el-form>
    <div class="jobs-table-wrapper">
      <el-table 
        :data="tableData.records" 
        style="width: 100%;" 
        height="100%"
        v-loading="loading"
        element-loading-text="加载中..."
        :empty-text="loading ? '' : '暂无数据'"
      >
        <el-table-column prop="name" label="岗位名称" show-overflow-tooltip />
        <el-table-column prop="teacherName" label="发布教师" show-overflow-tooltip />
        <el-table-column prop="teacherCollege" label="所属院系" show-overflow-tooltip />
        <el-table-column prop="description" label="工作内容" show-overflow-tooltip min-width="200" />
        <el-table-column prop="location" label="工作地点" show-overflow-tooltip />
        <el-table-column prop="salary" label="薪资" width="120">
          <template #default="{ row }">
            {{ row.salary }} 元/小时
          </template>
        </el-table-column>
        <el-table-column prop="time" label="工作时间" show-overflow-tooltip min-width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'info'" effect="plain">
              {{ row.status === 0 ? '可申请' : '不可申请' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="tableData.total"
        :page-size="filters.size"
        :current-page="filters.page"
        @current-change="handlePageChange"
      />
    </div>
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      :close-on-click-modal="false"
      @closed="formRef?.resetFields()"
    >
      <el-form 
        :model="form" 
        :rules="rules"
        ref="formRef" 
        label-width="100px"
        class="dialog-form"
        @submit.prevent
      >
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="工作内容" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入工作内容" 
          />
        </el-form-item>
        <el-form-item label="工作地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入工作地点" />
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input-number 
            v-model="form.salary" 
            :min="0"
            :precision="2"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入薪资(元/小时)"
          />
        </el-form-item>
        <el-form-item label="工作时间" prop="time">
          <el-input v-model="form.time" placeholder="请输入工作时间，如：周一至周五 9:00-18:00" />
        </el-form-item>
        <el-form-item label="发布教师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择发布教师" style="width: 100%">
            <el-option 
              v-for="teacher in teachers" 
              :key="teacher.id" 
              :label="teacher.username + ' - ' + teacher.college" 
              :value="teacher.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">可申请</el-radio>
            <el-radio :label="1">不可申请</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
.jobs-page {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.filter-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.jobs-table-wrapper {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  min-height: 500px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  --el-table-border-color: var(--el-border-color-lighter);
}

:deep(.el-table th) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-input) {
  border-radius: 4px;
}

:deep(.el-select) {
  border-radius: 4px;
}

:deep(.el-pagination) {
  justify-content: center;
  width: 100%;
}

.dialog-form {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 20px;
}

:deep(.el-dialog) {
  border-radius: 8px;
}
</style>

